//
//  CitySelectViewController.m
//  myhuibao
//
//  Created by li jun on 13-7-27.
//  Copyright (c) 2013年 myhuibao. All rights reserved.
//

#import "CitySelectViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "SBJson.h"
#import "config.h"
#import "OMGToast.h"
#define kSectionSelectorWidth 20
@interface CitySelectViewController ()

@end

@implementation CitySelectViewController
@synthesize cities,arrayCity,reqCity;
//@synthesize sections;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
   
       self.view.backgroundColor = [UIColor scrollViewTexturedBackgroundColor];
    
    return self;
}
//////////////////////////////////////////////////////////////////////////
#pragma mark - SectionSelectionView DataSource

// Tell the datasource how many sections we have - best is to forward to the tableviews datasource
-(NSInteger)numberOfSectionsInSectionSelectionView:(CHSectionSelectionView *)sectionSelectionView
{
    return [_testTableView.dataSource numberOfSectionsInTableView:_testTableView];
}

// Create a nice callout view so that you see whats selected when
// your finger covers the sectionSelectionView
-(UIView *)sectionSelectionView:(CHSectionSelectionView *)selectionView callOutViewForSelectedSection:(NSInteger)section
{
    UILabel *label = [[UILabel alloc] init];
    
    label.frame = CGRectMake(0, 0, 80, 80); // you MUST set the size of the callout in this method
    
    // do some ui stuff
    
    label.backgroundColor = [UIColor whiteColor];
    label.textColor = [UIColor redColor];
    label.font = [UIFont boldSystemFontOfSize:40];
    NSString *title =  [sections objectAtIndex:section];//[_testTableView.dataSource tableView:_testTableView titleForHeaderInSection:section];
    if([title isEqualToString:@"热门城市"])
        title = @"#";
    label.text = title;//[_testTableView.dataSource tableView:_testTableView titleForHeaderInSection:section];
    label.textAlignment = UITextAlignmentCenter;
    
    // dont use that in your code cause layer shadows are
    // negatively affecting performance
    
    [label.layer setCornerRadius:label.frame.size.width/2];
    [label.layer setBorderColor:[UIColor darkGrayColor].CGColor];
    [label.layer setBorderWidth:3.0f];
    [label.layer setShadowColor:[UIColor blackColor].CGColor];
    [label.layer setShadowOpacity:0.8];
    [label.layer setShadowRadius:5.0];
    [label.layer setShadowOffset:CGSizeMake(2.0, 2.0)];
    
    return label;
}


// Create the view that is displayed inside the sectionSelectionView
// This is basically our letter index. CHSectionSelectionItemView subclass
// should be used here. The frame of the view is set by the sectionSelectionView
// it takes its, width and height/numberOfSections for the height
-(CHSectionSelectionItemView *)sectionSelectionView:(CHSectionSelectionView *)selectionView sectionSelectionItemViewForSection:(NSInteger)section
{
    DemoSectionItemSubclass *selectionItem = [[DemoSectionItemSubclass alloc] init];
    NSString *title =  [sections objectAtIndex:section];//[_testTableView.dataSource tableView:_testTableView titleForHeaderInSection:section];
    if([title isEqualToString:@"热门城市"])
        title = @"#";
    selectionItem.titleLabel.text = title;
    selectionItem.titleLabel.font = [UIFont systemFontOfSize:14];
    selectionItem.titleLabel.textColor = [UIColor darkGrayColor];
    selectionItem.titleLabel.highlightedTextColor = [UIColor redColor];
    selectionItem.titleLabel.shadowColor = [UIColor whiteColor];
    selectionItem.titleLabel.shadowOffset = CGSizeMake(0, 1);
    
    return selectionItem;
}

//////////////////////////////////////////////////////////////////////////
#pragma mark - SectionSelectionView Delegate

// Jump to the selected section in our tableview
-(void)sectionSelectionView:(CHSectionSelectionView *)sectionSelectionView didSelectSection:(NSInteger)section
{
    [_testTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:section] atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

//////////////////////////////////////////////////////////////////////////
#pragma mark - TableView Delegate

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSString *title = [sections objectAtIndex:section];
    if([title isEqualToString:@"#"])
        title = @"热门城市";
    else if(section==1)
        title = @"全部城市";
    else
        title = @"";
    return title;
}

//////////////////////////////////////////////////////////////////////////
#pragma mark - TableView DataSource

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
        cell.contentView.backgroundColor = [UIColor whiteColor];
        cell.textLabel.backgroundColor = [UIColor clearColor];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.textLabel.font= [UIFont systemFontOfSize:14];
        
    }
    NSString *key = [sections objectAtIndex:indexPath.section];
    NSDictionary * city = [[cities objectForKey:key] objectAtIndex:indexPath.row];
    cell.textLabel.text = [city objectForKey:@"cityName"];//[cellData objectAtIndex:indexPath.row];
    
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor redColor];
    cell.selectedBackgroundView = bgView;
    
    return cell;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    //    return [cellData count];
    NSString *key = [sections objectAtIndex:section];
    NSArray *citySection = [cities objectForKey:key];
    return [citySection count];
    
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [sections count];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    curSection = indexPath.section;
    curRow = indexPath.row;
    NSString *key = [sections objectAtIndex:curSection];
    NSArray *citySection = [cities objectForKey:key];
    NSDictionary *item = [citySection objectAtIndex:curRow];
    if([[item objectForKey:@"status"]intValue]==1){
        [[Config Instance]setCityId:[[item objectForKey:@"cityID"]intValue]];
        [[Config Instance]setCity:[item objectForKey:@"cityName"]];
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [OMGToast showWithText:@"城市尚未开通，敬请期待！" bottomOffset:100 duration:3];
    }
}
- (void) getCity{
    //异步请求
    NSURL *url = [NSURL URLWithString:url_city];
    reqCity = [ASIHTTPRequest requestWithURL:url];
    [reqCity setShouldAttemptPersistentConnection:NO];
    [reqCity setDidFinishSelector:@selector(finishCity:)];
    isCityFinished = false;
    [reqCity setDelegate: self];
    
    if (!loadingView.bFirstRequest) {
        [reqCity startAsynchronous];
    }
}

- (void)finishCity:(ASIHTTPRequest *)request
{
    NSString *jsonStr = [request responseString];
    NSDictionary *dic = [jsonStr JSONValue];
    arrayCity = [dic valueForKey:@"data"];
    isCityFinished = true;
    
//    cities = [[NSDictionary alloc]
//              initWithContentsOfFile:path];//[NSArray arrayWithObjects:@"Test 1",@"Test 2",@"Test 3",@"Test 4",@"Test 42",@"Test 5", nil];
    cities = [[NSMutableDictionary alloc]init];
    NSMutableArray *hots = [[NSMutableArray alloc] init];
    for(int i=0;i<arrayCity.count;i++){
        NSDictionary *city = [arrayCity objectAtIndex:i];
        int isHot = [[city objectForKey:@"isHot"]intValue];
        if(isHot==1)
            [hots addObject:city];
    }
    [cities setValue:hots forKey:@"#"];

    for(int i=0;i<arrayCity.count;i++){
        NSDictionary *city = [arrayCity objectAtIndex:i];
        NSString * cityCode = [city objectForKey:@"cityCode"];
        NSString *first = [[cityCode substringToIndex:1] uppercaseString];
        NSMutableArray * array = [cities objectForKey:first];
        if (array.count==0) {
            array = [[NSMutableArray alloc] init];
            [array addObject:city];
            [cities setValue:array forKey:first];
        }else{
            [array addObject:city];
        }
    }

    sections = [[cities allKeys] sortedArrayUsingSelector:
                @selector(compare:)]; //
    //    sections = [NSArray arrayWithObjects:@"#",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil];
    sections = [[NSArray alloc] initWithArray:sections];
    //NSLog(@"%@",sections);
    
    _testTableView = [[UITableView alloc] init];
    _testTableView.dataSource = self;
    _testTableView.delegate = self;
    //    _testTableView.sectionHeaderHeight=0;
    [self.view addSubview:_testTableView];
    
    _selectionView = [[CHSectionSelectionView alloc] init];
    _selectionView.backgroundColor = [UIColor colorWithRed:248.0/255.0 green:248.0/255.0 blue:248.0/255.0 alpha:1.0];
    _selectionView.dataSource = self;
    _selectionView.delegate = self;
    _selectionView.showCallouts = YES; // the view should show a callout when an item is selected
    _selectionView.calloutDirection = SectionCalloutDirectionLeft; // Callouts should appear on the right side
    _selectionView.calloutPadding = 20;
    [self.view addSubview:_selectionView];
    

//    NSLog(@"%@",arrayCity);
    
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    NSError *error = [request error];
    NSLog(@"%@",error);
    if (error.code==net_failure_code) {
        [OMGToast showWithText:net_failure_msg bottomOffset:100];
    }
    isCityFinished = true;
}
//////////////////////////////////////////////////////////////////////////
#pragma mark - View Stuff

- (void)startRequest
{
    if(!loadingView){
        
        loadingView = [[RequestLoadingView alloc]
                               initRequestLoadingView:self
                                   queueFinishSelector:nil
                                      viewFrame:LoadingViewFrame];
    }
    
    [self getCity];
    
    [loadingView addRequestToQueue:reqCity];
    
    [loadingView startRequestQueue];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self startRequest];
    
    NSString *title = [NSString stringWithFormat:@"   %@",[[Config Instance] getLocateCity]];
    [_btnLocation setTitle: title forState:UIControlStateNormal];
    
	// Do any additional setup after loading the view.
//    NSString *path=[[NSBundle mainBundle] pathForResource:@"citydict"
//                                                   ofType:@"plist"];
        _testTableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
    [_selectionView reloadSections];
}

-(void)viewWillLayoutSubviews
{
    [super viewWillLayoutSubviews];
    
    _testTableView.frame = CGRectMake(0, 90, self.view.bounds.size.width-kSectionSelectorWidth, self.view.bounds.size.height-90);
    _selectionView.frame = CGRectMake(self.view.bounds.size.width-kSectionSelectorWidth, 36, kSectionSelectorWidth, self.view.bounds.size.height-36);
}


-(BOOL)shouldAutorotate
{
    return YES;
}
/*
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}
*/
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    [self setBtnLocation:nil];
    [super viewDidUnload];
}
- (IBAction)doBack:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
-(void) viewWillDisappear:(BOOL)animated
{
    if(!isCityFinished){
        [reqCity clearDelegatesAndCancel];
        [reqCity cancel];
    }
    [ super viewWillDisappear:animated];
}

- (IBAction)selectLocation:(id)sender {
    bool found=false;
    int cityId,status;
    NSString *cityName;
    for(int i=0;i<arrayCity.count;i++){
        NSDictionary *item = [arrayCity objectAtIndex:i];
        cityName = [item objectForKey:@"cityName"];
        cityId = [[item objectForKey:@"cityID"]intValue];
        status = [[item objectForKey:@"status"]intValue];
        NSRange textRange;
        textRange =[[[Config Instance]getLocateCity] rangeOfString:cityName];
        if(textRange.location != NSNotFound)
        {
            found = true;
            break;
        }else
            continue;
    }
    if(found){
        if(status==1){
            [[Config Instance]setCityId:cityId];
            [[Config Instance]setCity:cityName];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [OMGToast showWithText:@"城市尚未开通，敬请期待！" bottomOffset:100 duration:3];
        }
    }else
        [OMGToast showWithText:@"城市尚未开通，敬请期待！" bottomOffset:100 duration:3];

}
@end
